﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;

namespace Yelper.Web.Controllers {

    public class AjaxController : Controller {

        /// <summary>
        /// Returns all Idols that match the filter (Used in AJAX-Requests)
        /// </summary>
        [Authorize]
        public ActionResult Users(string filter) {
               using (yelperEntities entities = new yelperEntities())
                {
                    // Get current user
                    var user = entities.Users.Where(u => u.Username == HttpContext.User.Identity.Name).SingleOrDefault();

                    // Return 400-error when user is not found (should not happen, but might happen in another universe)
                    if (user == null)
                        return new HttpStatusCodeResult(400);
                    
                    // Get a list of all Idols that match the filter
                    var users = user.Idols.Where(u => u.Username.StartsWith(filter)).ToList();

                    // Return 405 when no users are found (405 is catched in the AJAX)
                    if (users.Count == 0)
                        return new HttpStatusCodeResult(405);   // Don't change to another errorcode without changing the AJAX

                    // Add users to the ViewModel
                    ViewData.Model = users;
                }

                return View();
        }
        
        /// <summary>
        /// Posts a new Yelp as the current user. (Used in AJAX-Requests)
        /// </summary>
        [HttpPost]
        [Authorize]
        public ActionResult Yelp(FormCollection form) {
            if (Request.IsAjaxRequest()) {

                string message = form["Yelp"];

                if (message != string.Empty && message.Length <= 141) {

                    Yelp yelp;

                    using (yelperEntities entities = new yelperEntities()) {
                        // Get current user
                        var user = entities.Users.Where(u => u.Username == HttpContext.User.Identity.Name).SingleOrDefault();

                        if (!user.Activated) return new HttpStatusCodeResult(403);

                        // Return 400-error when user is not found (should not happen, but might happen in another universe)
                        if (user == null)
                            return new HttpStatusCodeResult(400);

                        // Create a new Yelp
                        yelp = new Yelp {
                            UserId = user.UserId,
                            Message = message.Replace('#', 'λ'),
                            YelpDate = DateTime.UtcNow
                        };

                        // Add & Save Yelp to database
                        entities.Yelps.AddObject(yelp);
                        entities.SaveChanges();

                    }

                    return PartialView("YelpPartial", yelp);

                } else {
                    return new HttpStatusCodeResult(400);
                }

            } else {
                return HttpNotFound();
            }

        }

        // Remote validation: check if username is available
        [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
        public JsonResult CheckUsernameAvailable(string Username) {
            bool available = false;
            using (yelperEntities entities = new yelperEntities()) {
                available = entities.Users.Where(x => x.Username == Username).Count() == 0;
            }
            return Json(available,JsonRequestBehavior.AllowGet);
        } 

        [Authorize]
        public ActionResult ToggleGroupie(string Username) {
            if (Request.IsAjaxRequest()) {
                string message;
                string currentuser = User.Identity.Name;
                using (yelperEntities entities = new yelperEntities()) {
                    User me = entities.Users.Where(x => x.Username == currentuser).Single();
                    bool IsIdol = me.Idols.Where(x => x.Username == Username).Count() == 1;
                    if (IsIdol) {
                        User idol = me.Idols.Where(x => x.Username == Username).Single();
                        me.Idols.Remove(idol);
                        message = Username + " is no longer one of your idols";
                    } else {
                        User idol = entities.Users.Where(x => x.Username == Username).Single();
                        me.Idols.Add(idol);
                        message = Username + " was added to your list of idols";
                    }
                    entities.SaveChanges();
                }
                return Content(message);
            } else {
                return HttpNotFound();
            }
        } 

    }
}
